import user from '../user.js';
import { toTimeString } from '../util.js';

export default {
  data() {
    return {
      areaRow: user.settingList.areaRow.value,
      hidePassed: false,
      taskList: user.taskList,
      timeBoxList: user.timeBoxList,
    }
  },
  template:/* html */`
    <div class="tab box-tab">
      <div class="subnav">
        <button @click="hide">
          {{ hidePassed ? '显示' : '隐藏' }}已过去的时间段
        </button>
        <button @click="clear">删除全部</button>
      </div>
      <div class="time-box-list">
        <div
          class="card"
          v-for="(timeBox,index) in sortTimeList"
          :key="index"
        >
          <h2 class="open">{{ toTimeString(timeBox) }}</h2>
          <textarea
            :rows="areaRow"
            class="task-input"
            v-model="timeBox.task"
          ></textarea>
          <div class="buttom button-list">
            <button @click="clearBox(index)">清空</button>
            <button @click="removeBox(index)">删除</button>
          </div>
        </div>
      </div>
    </div>
  `,
  computed: {
    sortTimeList() {
      let dayStartTime = user.settingList.startDayTime.value
      this.timeBoxList.sort((a, b) =>
        delTime(a.start, b.start, dayStartTime)
      );
      if (this.hidePassed) {
        let now = new Date();
        let nowTime = now.getHours() * 60 + now.getMinutes();
        return this.timeBoxList.filter(x =>
          delTime(x.end - 0.1, nowTime, dayStartTime) >= 0
        );
      }
      return this.timeBoxList;
    }
  },
  methods: {
    save() {
      user.save('timeBoxList');
    },

    hide() {
      this.hidePassed = !this.hidePassed;
    },

    clear() {
      this.timeBoxList.splice(0);
    },

    clearBox(index) {
      this.timeBoxList[index].task = '';
    },

    removeBox(index) {
      this.timeBoxList.splice(index, 1);
    },

    toTimeString,
  },
  watch: {
    timeBoxList: {
      deep: true,
      handler() {
        this.save();
      }
    }
  }
}

function delTime(a, b, dayStartTime) {
  [a, b] = [a, b]
    .map(x => x < dayStartTime * 60 ? x + 60 * 24 : x);
  return a - b;
}
